from fastapi import FastAPI, Depends, HTTPException, status, Request
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from fastapi.openapi.models import OAuthFlows as OAuthFlowsModel, OAuthFlowPassword
from fastapi.openapi.models import APIKey, APIKeyIn
from fastapi.openapi.models import SecurityScheme as SecuritySchemeModel
from fastapi.openapi.utils import get_openapi
from fastapi.middleware.cors import CORSMiddleware
import time

app = FastAPI()

# 定义一个 OAuth2PasswordBearer 实例，用于获取访问令牌

# 模拟的用户数据，实际情况下需要从数据库或其他地方获取
fake_users_db = {
    "user": {
        "username": "user",
        "password": "password",
    }
}


@app.post("/token")
async def login(token: str = None):
    return {"access_token": "fake-access-token", "token_type": "bearer"}


# 路由，需要身份验证
@app.get("/items/")
async def read_items():
    return {"token": "token", "items": [{"item": "Foo"}, {"item": "Bar"}]}


@app.get("/items2/")
async def read_items2():
    return {"token": 'wefef', "items": [{"item": "Foo"}, {"item": "Bar"}]}


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    # (b'authorization', b'awefawef')
    # (b'authorization', b'Bearer woshiqingqiutou')
    header = request.headers
    print("csrftoken", header.keys(), header.values())
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    print("本次耗时", process_time)
    return response


# 修改默认的Swagger UI配置
def custom_openapi():
    if app.openapi_schema:
        return app.openapi_schema
    openapi_schema = get_openapi(
        title="Custom API",
        version="1.0.0",
        summary="AAauthorization",
        description="This is a very custom OpenAPI schema",
        routes=app.routes,
    )
    openapi_schema["components"]["securitySchemes"] = {
        "BearerAuth": {
            "type": "http",
            "scheme": "bearer",
            "bearerFormat": "JWT",
            "in": "header",
            "name": "AAauthorization",
        }
    }
    openapi_schema["security"] = [{"BearerAuth": []}]
    app.openapi_schema = openapi_schema
    return app.openapi_schema


app.openapi = custom_openapi

# # 配置CORS以允许跨源请求（例如从本地主机访问API）
# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=["*"],
#     allow_credentials=True,
#     allow_methods=["*"],
#     allow_headers=["*"],
# )

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=8001)
